package org.jeecg.modules.utils;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.enmu.AttributeLength;
import org.jeecg.modules.enmu.MessageTypeEnum;
import org.jeecg.modules.vo.Message;

import java.util.List;

@Slf4j

public class CustomMessageDecoder extends ByteToMessageDecoder {

    private static final int HEADER_LENGTH = 10; // 包头标志4字节 + 消息类型2字节 + 消息长度4字节
    public static final int MAGIC_NUMBER = 0x7E7C6B5A;

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        //可读字节数
        if (in.readableBytes() < HEADER_LENGTH) {
            // 不足一个完整消息头，等待更多数据
            return;
        }
        int byteLength = in.readableBytes();
        // 保存当前读指针位置
        int currentPointer = in.readerIndex();
        ByteBuf copy = in.copy();
        byte[] data = new byte[byteLength];
        copy.readBytes(data);
        //将字节转为hesh
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < byteLength; i++) {
            sb.append(String.format("%02X", data[i] & 0xFF));
        }
        log.info("接收消息内容：" + sb.toString());
        // 读取包头标志
        int magicNumber = in.readIntLE();
        if (magicNumber != MAGIC_NUMBER) {
            in.readerIndex(currentPointer);
            log.info("包头标志不匹配: " + magicNumber);
            return;
        }
        // 读取消息长度
        int messageLength = in.readIntLE();
        if (byteLength < messageLength) {
            // 不足一个完整消息体，恢复读指针位置，等待更多数据
            in.readerIndex(currentPointer);
            log.debug("消息长度错误:" + messageLength);
            return;
        }
        // 读取消息序号
        int SerialsNo = in.readIntLE();
        int messageType = in.readIntLE();
        Message message = new Message();
        message.setMessageType(messageType);
        message.setBuffer(in);
        out.add(message);
        log.info("接收消息类型：" + MessageTypeEnum.fromValue(message.getMessageType()).getDescription());
        log.info("接收消息长度：" + byteLength);
    }
}